<template>
  <el-checkbox-group>
    <el-checkbox v-for="item in roles" :key="item.id" :label="item.name" :value="item.name" />
  </el-checkbox-group>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import useUserStore from '@/stores/modules/user';
import pinia from '@/stores';
import { analysisAccessToken } from '@/utils/token';
import { getUserRolesAsync } from '@/utils/api/user';
import { propTypes } from '@/utils/propTypes';
import type { IdentityRoleDto } from '@/utils/api/role/type';
import { getAllAsync } from '@/utils/api/role';

const props = defineProps({
  isLoadAll: propTypes.bool.def(false)
});

const userStore = useUserStore(pinia);
const roles = ref<IdentityRoleDto[]>([]);
onMounted(async () => {
  if (props.isLoadAll) {
    await initAllRolesAsync();
    return;
  }

  const token = userStore.token!;
  const payloadObj = analysisAccessToken(token.accessToken);
  const roleList = await getUserRolesAsync(payloadObj.sub);
  roles.value = roleList.items;
});

//初始化角色
const initAllRolesAsync = async () => {
  // 获取所有角色
  const roleListStr = await getAllAsync();
  const array = new Array<IdentityRoleDto>();
  roleListStr.forEach((item: any) => {
    let identityRoleDto: IdentityRoleDto = {
      id: '',
      name: item,
      isDefault: false,
      isPublic: false,
      isStatic: false
    };
    array.push(identityRoleDto);
  });
  roles.value = array;
};
</script>
